import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
    { name: '神领物流 - 登录', path: '/login', component: () => import('@/views/Login/Login.vue') },
    {
        path: '/',
        redirect: '/dashboard',
        component: () => import('@/views/Layout.vue'),
        children: [
            { name: '工作台', path: '/dashboard', component: () => import('@/views/Dashboard/Dashboard.vue') },
            { name: '机构管理', path: '/data-management/organization', component: () => import('@/views/DataManagement/Organization.vue') },
            { name: '机构作业范围', path: '/data-management/work-scope', component: () => import('@/views/DataManagement/WorkScope.vue') },
            { name: '运费管理', path: '/data-management/freight', component: () => import('@/views/DataManagement/Freight.vue') },
            { name: '车型管理', path: '/car-management/model', component: () => import('@/views/CarManagement/Model.vue') },
            { name: '车辆列表', path: '/car-management/list', component: () => import('@/views/CarManagement/List.vue') },
            { name: '车辆详情', path: '/car-management/list/:id', component: () => import('@/views/CarManagement/Detail.vue') },
            { name: '回车登记', path: '/car-management/register', component: () => import('@/views/CarManagement/Register.vue') },
        ]
    }
]

const router = new VueRouter({
    routes
})

const whiteList = ['/login', '/404']
router.beforeEach((to, from, next) => {
    document.title = to.name
    NProgress.start()
    store.commit('setPageLoading', true)
    const token = store.state.user.token
    if (token) {
        if (to.path === '/login') {
            next()
        } else {
            next()
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

export default router
